package ru.tulupov.quadraticequation;

import java.util.ArrayList;
import java.util.List;

/**
 * Quadratic equation solver
 * 
 * @author <a href="mailto:zhekka3@gmail.com">Eugene Tulupov</a>
 */
public class QuadraticEquationSolver {
	private static final double EPSILON = 1e-9;
	private QuadraticEquation equation;
	private List<Double> roots;

	/**
	 * Solves a quadratic equation.
	 */
	public QuadraticEquationSolver(QuadraticEquation equation) {
		this.equation = equation;
		solve();
	}

	/**
	 * @return the list of roots.
	 */
	public List<Double> getRoots() {
		return roots;
	}

	private void solve() {
		roots = new ArrayList<Double>();

		double a = equation.getA();
		double b = equation.getB();
		double c = equation.getC();

		double discriminant = b * b - 4 * a * c;

		if (Math.abs(discriminant) < EPSILON) {
			// Discriminant is zero, the equation has one root.
			roots.add((-b) / (2.0 * a));
		} else if (discriminant > 0) {
			// Discriminant is positive, the equation has two roots.
			roots.add((-b + Math.sqrt(discriminant)) / (2.0 * a));
			roots.add((-b - Math.sqrt(discriminant)) / (2.0 * a));
		} else {
			// Discriminant is negative, the equation hasn't rational roots.
		}
	}

}
